package net.ck.hzq;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import Bean.MyearningsBean;
import Bean.MyearningsParamBean;
import Utils.CheckPhoneNumberUtils;
import Utils.HelloWordModel;
import Utils.StringUtil;
import Utils.SystemDatas;
import activity.AllyRewardActivity;
import base.BaseAct;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import cn.finalteam.loadingviewfinal.ScrollViewFinal;
import event.LoginEvent;
import event.NetErrorEvent;
import retrofit2.Call;
import retrofit2.Response;
import ui.activity.mine.MyWalletAct;
import ui.activity.profit.HistoricalIncomeAct;

public class MyEarningsActivity extends BaseAct implements View.OnClickListener {

    private TextView myearnings_tohistoryincome, myearnings_txt, myearnings_txt00, myearnings_txt01, myearnings_txt02,
            myearnings_txt03, myearnings_txt04, myearnings_txt05;

    private TextView myearnings_incomesettlement, myearnings_txt1, myearnings_txt7;

    private ImageView myearnings_back, myearnings_img;

//    String[] name0 = {"拓展奖励", "推广奖励", "团建津贴", "管理津贴"};
//    String[] name1 = {"0.00", "0.00", "0.00", "0.00"};
//    String[] name2 = {"+0", "+0", "+0", "+0"};
//    String[] name3 = {"0.00", "0.00", "0.00", "0.00"};
//    String[] name4 = {"+0.00", "+0.00", "+0.00", "+0.00"};
//    String[] name5 = {"0.00", "0.00", "0.00", "0.00"};
//    String[] name6 = {"+0.00", "+0.00", "+0.00", "+0.00"};

    public static String[] s;
    public static double[] d;

    private LinearLayout myearnings_linear, myearnings_item_linear;

    private ImageView wideArrow;
    private ImageView spreadArrow;
    private ImageView tbArrow;
    private ImageView manageArrow;
    private TextView wideTotalAmount, wideTotalBenefit,chengzhangamount,tuoxinamount,lingdaoamount;
    private TextView spreadTotalAmount, spreadTotalBenefit, spreadMAmount, spreadMBenefit, spreadTAmount, spreadTBenefit;
    private TextView chengzhangBenefit,tuoxinBenefit,lingdaoBenefit;
    private TextView adjustAmount;
    ScrollViewFinal sv;
    PtrClassicFrameLayout ptr;
    private LineChart chart;

    private SharedPreferences sp;

    @Override
    protected void setRoot() {
        setContentView(R.layout.activity_myearnings);
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);
        TobuyApplication.getmInstance().onActivityCreate(this);
        sv = findViewById(R.id.sv);
        ptr = findViewById(R.id.ptr_layout);
        myearnings_txt00 = (TextView) findViewById(R.id.myearnings_txt00);
        myearnings_txt01 = (TextView) findViewById(R.id.myearnings_txt01);
        myearnings_txt02 = (TextView) findViewById(R.id.myearnings_txt02);
        myearnings_txt03 = (TextView) findViewById(R.id.myearnings_txt03);
        myearnings_txt04 = (TextView) findViewById(R.id.myearnings_txt04);
        myearnings_txt05 = (TextView) findViewById(R.id.myearnings_txt05);
        myearnings_linear = (LinearLayout) findViewById(R.id.myearnings_linear);
        myearnings_item_linear = (LinearLayout) findViewById(R.id.myearnings_item_linear);
        myearnings_txt7 = (TextView) findViewById(R.id.myearnings_txt7);
        myearnings_txt = (TextView) findViewById(R.id.myearnings_txt);
        myearnings_tohistoryincome = (TextView) findViewById(R.id.myearnings_tohistoryincome);
        myearnings_txt7.setText(CheckPhoneNumberUtils.getLast12Months(0) + "月预期收益(元）");
        myearnings_txt1 = (TextView) findViewById(R.id.myearnings_txt1);
        myearnings_back = (ImageView) findViewById(R.id.myearnings_back);
        myearnings_incomesettlement = (TextView) findViewById(R.id.myearnings_incomesettlement);
        myearnings_incomesettlement.getBackground().setAlpha(100);

        myearnings_linear.setOnClickListener(this);
        myearnings_back.setOnClickListener(this);
        myearnings_tohistoryincome.setOnClickListener(this);
        myearnings_incomesettlement.setOnClickListener(this);

        adjustAmount = findViewById(R.id.adjust_amount);

        // 扩展奖励
        chengzhangamount = findViewById(R.id.chengzhang_total_amount);
        chengzhangBenefit = findViewById(R.id.chengzhang_total_benefit);
        tuoxinamount = findViewById(R.id.tuoxin_total_amount);
        tuoxinBenefit = findViewById(R.id.tuoxin_total_benefit);
        lingdaoamount = findViewById(R.id.lingdao_total_amount);
        lingdaoBenefit = findViewById(R.id.lingdao_total_benefit);

        // 扩展奖励

        wideTotalAmount = findViewById(R.id.wide_total_amount);
        wideTotalBenefit = findViewById(R.id.wide_total_benefit);



        // 推广奖励
        spreadTotalAmount = findViewById(R.id.spread_total_amount);
        spreadTotalBenefit = findViewById(R.id.spread_total_benefit);


        initChart();
        sv.setOnLoadMoreListener(() -> {
        });
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                sv.setVisibility(View.GONE);
                initData();
            }
        });
        ptr.autoRefresh(true);
    }

    private void initChart() {
        chart = findViewById(R.id.line_chart);
        // background color
        chart.setBackgroundColor(Color.WHITE);
        // disable description text
        chart.getDescription().setEnabled(false);
        // enable touch gestures
        chart.setTouchEnabled(false);
        // set listeners
//        chart.setOnChartValueSelectedListener(this);
        chart.setDrawGridBackground(false);
        // enable scaling and dragging
        chart.setDragEnabled(false);
        chart.setScaleEnabled(false);
        // force pinch zoom along both axis
        chart.setPinchZoom(true);

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = chart.getXAxis();
            // vertical grid lines
//            xAxis.enableGridDashedLine(10f, 10f, 0f);
            Calendar today = Calendar.getInstance(Locale.SIMPLIFIED_CHINESE);
            int month = today.get(Calendar.MONTH);
            today.add(Calendar.MONTH, -1);
            int month1 = today.get(Calendar.MONTH);
            today.add(Calendar.MONTH, -1);
            int month2 = today.get(Calendar.MONTH);
            today.add(Calendar.MONTH, -1);
            int month3 = today.get(Calendar.MONTH);
            today.add(Calendar.MONTH, -1);
            int month4 = today.get(Calendar.MONTH);
            xAxis.setLabelCount(6, true);
            IndexAxisValueFormatter vf = new IndexAxisValueFormatter();
            vf.setValues(new String[]{"" + (month4 + 1), "" + (month3 + 1), "" + (month2 + 1), "" + (month1 + 1),
                    "" + (month + 1), ""});
            xAxis.setValueFormatter(vf);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setDrawGridLines(false);
        }
        YAxis yAxis;
        {   // // Y-Axis Style // //
            yAxis = chart.getAxisLeft();
            // disable dual axis (only use LEFT axis)
            chart.getAxisRight().setEnabled(false);
            yAxis.setLabelCount(5, false);
            yAxis.setDrawAxisLine(false);
            yAxis.setDrawGridLines(true);
            yAxis.setDrawLabels(false);

        }
        // draw points over time
        chart.animateX(1500);
        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();
        // draw legend entries as lines
        l.setForm(Legend.LegendForm.NONE);
    }

    private void setData(List<Entry> values) {
        LineDataSet set1;
        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            set1.notifyDataSetChanged();
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "");
            set1.setDrawIcons(false);
            // black lines and points
            set1.setColor(getResources().getColor(R.color.blue_2ba9e4));
            set1.setCircleColor(getResources().getColor(R.color.blue_2ba9e4));
            // line thickness and point size
            set1.setLineWidth(2f);
            set1.setCircleRadius(2f);
            // draw points as solid circles
            set1.setDrawCircleHole(false);
            // text size of values
            set1.setValueTextSize(9f);
            set1.setValueTextColor(getResources().getColor(R.color.blue_2ba9e4));
            set1.setValueFormatter((value, entry, dataSetIndex, viewPortHandler) -> {
                if (entry.getX() == 5) {
                    return "";
                }
                return StringUtil.getFormatPrice(value);
            });
            ArrayList<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1); // add the data sets
            // create a data object with the data sets
            LineData data = new LineData(dataSets);
            // set data
            chart.setData(data);
        }
    }

    private void initData() {
        loading(true);
        MyearningsParamBean m = new MyearningsParamBean();
//        m.setCustomId(Integer.parseInt(sp.getString("id", null)));
        m.setCustomId(sp.getString("id", "0"));
        Call<MyearningsBean> userMsgCall = HelloWordModel.getInstance(MyEarningsActivity.this).getMyearnings(SystemDatas
                .GetService_URL("getMyearnings"), m);
        userMsgCall.enqueue(new retrofit2.Callback<MyearningsBean>() {
            @Override
            public void onResponse(Call<MyearningsBean> call, final Response<MyearningsBean> response) {
                try {
                    if (response.body() == null || !response.body().getMsg().equals("success")) {
                        Toast.makeText(MyEarningsActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    } else if (response.body() != null && "401".equals(response.body().getResult())) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else {
                        MyearningsBean.DataBean data = response.body().getData();
                        ArrayList<Entry> values = new ArrayList<>();
                        Float monthsy = Float.valueOf(StringUtil.getFormatPrice(data.getMonthsy()));
                        Float monthsy1 = Float.valueOf(StringUtil.getFormatPrice(data.getMonthsy1()));
                        Float monthsy2 = Float.valueOf(StringUtil.getFormatPrice(data.getMonthsy2()));
                        Float monthsy3 = Float.valueOf(StringUtil.getFormatPrice(data.getMonthsy3()));
                        Float monthsy4 = Float.valueOf(StringUtil.getFormatPrice(data.getMonthsy4()));
                        values.add(new Entry(0, monthsy4, getResources().getDrawable(R.mipmap.icon_add)));
                        values.add(new Entry(1, monthsy3, getResources().getDrawable(R.mipmap.icon_add)));
                        values.add(new Entry(2, monthsy2, getResources().getDrawable(R.mipmap.icon_add)));
                        values.add(new Entry(3, monthsy1, getResources().getDrawable(R.mipmap.icon_add)));
                        values.add(new Entry(4, monthsy, getResources().getDrawable(R.mipmap.icon_add)));
                        values.add(new Entry(5, monthsy, getResources().getDrawable(R.mipmap.icon_add)));
                        YAxis yAxis = chart.getAxisLeft();
                        // axis range
//                        yAxis.setAxisMaximum(Math.max(10000f, 2 * Math.max(monthsy1, Math.max(monthsy2, Math.max(monthsy3, monthsy4)))));
                        yAxis.setAxisMaximum(Math.max(10000f, 1.5f * Math.max(monthsy1, Math.max(monthsy2, Math.max(monthsy3, monthsy4)))));
                        yAxis.setAxisMinimum(0f);
                        setData(values);
                        myearnings_txt.setText(data.getMonthsy() + "");
                        myearnings_txt1.setText(data.getAmountMoney() + "");
//                        name1 = new String[]{Double.parseDouble(data.getExpRewards()) / 10000 + "", Double.parseDouble(data
//                                .getProRewards()) / 10000 + "", Double.parseDouble(data.getRconAllowance()) / 10000 + "", Double
//                                .parseDouble(data.getManAllowance()) / 10000 + ""};
//                        name2 = new String[]{"+" + data.getExpRewardsSY(), "+" + data.getProRewardsSY(), "+" + data.getRconAllowanceSY
//                                (), "+" + data.getManAllowanceSY()};
//                        name3 = new String[]{Double.parseDouble(data.getExpRewardsSumMpos()) / 10000 + "", Double.parseDouble(data
//                                .getProRewardsSumMpos()) / 10000 + "", Double.parseDouble(data.getRconAllowanceSumMpos()) / 10000 + "",
//                                Double.parseDouble(data.getManAllowanceSumMpos()) / 10000 + ""};
//                        name4 = new String[]{"+" + data.getExpRewardsSumMposSY(), "+" + data.getProRewardsSumMposSY(), "+" + data
//                                .getRconAllowanceSumMposSY(), "+" + data.getManAllowanceSumMposSY()};
//                        name5 = new String[]{Double.parseDouble(data.getExpRewardsSumPos()) / 10000 + "", Double.parseDouble(data
//                                .getProRewardsSumPos()) / 10000 + "", Double.parseDouble(data.getRconAllowanceSumPos()) / 10000 + "",
//                                Double.parseDouble(data.getManAllowanceSumPos()) / 10000 + ""};
//                        name6 = new String[]{"+" + data.getExpRewardsSumPosSY(), "+" + data.getProRewardsSumPosSY(), "+" + data
//                                .getRconAllowanceSumPosSY(), "+" + data.getManAllowanceSumPosSY()};
                        myearnings_txt00.setText(data.getActRewards() + "");
                        myearnings_txt01.setText("+" + data.getActRewardsSY());
                        myearnings_txt02.setText(data.getActRewardsSumMpos() + "");
                        myearnings_txt03.setText("+" + data.getActRewardsSumMposSY());
                        myearnings_txt04.setText(data.getActRewardsSumPos() + "");
                        myearnings_txt05.setText("+" + data.getActRewardsSumPosSY());

                        adjustAmount.setText(data.adjMoney);

                        // 成长奖励
                        chengzhangamount.setText(data.czRewards);
                        chengzhangBenefit.setText("+" + data.czRewardsSY);

                        // 拓新奖励
                        tuoxinamount.setText(data.txRewards);
                        tuoxinBenefit.setText("+" + data.txRewardsSY);

                        // 领导奖励
                        lingdaoamount.setText(data.ldRewards);
                        lingdaoBenefit.setText("+" + data.ldRewardsSY);
                        // 直营奖励
                        wideTotalAmount.setText(data.expRewards);
                        wideTotalBenefit.setText("+" + data.expRewardsSY);
                        // 推广奖励
                        spreadTotalAmount.setText(data.proRewards);
                        spreadTotalBenefit.setText("+" + data.proRewardsSY);
                        // 团建奖励
                        // 管理奖励
                    }
                } catch (Exception e) {

                }
                sv.setVisibility(View.VISIBLE);
                ptr.onRefreshComplete();
                sv.onLoadMoreComplete();
                sv.setHasLoadMore(false);
                loading(false);
            }

            @Override
            public void onFailure(Call<MyearningsBean> call, Throwable t) {
                ptr.onRefreshComplete();
                sv.onLoadMoreComplete();
                sv.setHasLoadMore(false);
                loading(false);
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            // 合伙人分润详情
            case R.id.spread_detail_layout:
                intent = new Intent(this, AllyRewardActivity.class);
                startActivity(intent);
                break;
            case R.id.myearnings_back:
                finish();
                break;
            case R.id.myearnings_tohistoryincome:
                intent = new Intent(MyEarningsActivity.this, HistoricalIncomeAct.class);
                startActivity(intent);
                break;
            case R.id.myearnings_incomesettlement:
                intent = new Intent(MyEarningsActivity.this, MyWalletAct.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }
}
